﻿// ———————————————————————–
// <copyright file="SenderArgs.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// SenderArgs.cs - Helper Class for BackgroundWorker
// Project: ICNETSOA- HttpLoader
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2012
// Author:      Rob Gustafson The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2012 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

/// <summary>
/// Manages a cloning process for copying DEs from one server to another
/// </summary>

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml.Linq;

namespace HttpLoader
{
    class RouterCloner
    {
        IEnumerable<XElement> DEs = null;

        public void send(string source, string destination)
        {
            downloadAllDEXML(source);
            updateDateTimeSent(DateTime.Now);
            postAll(destination);
        }

        private void downloadAllDEXML(string source)
        {
            Console.WriteLine();
            Console.Write("downloading from "+source);
            string xml;
            using (var webClient = new WebClient())
            {
                xml = webClient.DownloadString(source+"/FeedService.svc/All/DEXML");
            }

            XDocument doc = XDocument.Parse(xml);
            DEs = doc.Descendants(XName.Get("EDXLDistribution", @"urn:oasis:names:tc:emergency:EDXL:DE:1.0"));

        }


        private void updateDateTimeSent(DateTime time)
        {
            // ex: 2012-03-10T13:30:10-05:00
            string dateAsString = time.ToString("yyyy-MM-ddTHH:mm:sszzz");

            foreach (XElement DE in DEs){         
                DE.Descendants(XName.Get("dateTimeSent", @"urn:oasis:names:tc:emergency:EDXL:DE:1.0")).First().SetValue(dateAsString);
            }
        }


        private void postAll(string destination)
        {
            HttpWebRequest request;
            HttpWebResponse resp;
            Console.WriteLine("");
            Console.Write("uploading to "+destination);
            foreach (XElement DE in DEs)
            {
                string s = DE.ToString();

                request = (HttpWebRequest)WebRequest.Create(destination + "/DEPostService.svc");
                request.KeepAlive = true;
                request.Method = "POST";
                request.ContentType = "text/xml";
                request.AllowAutoRedirect = true;
                request.ContentLength = Encoding.UTF8.GetByteCount(s);

                Stream requestStream = request.GetRequestStream();
                StreamWriter writer = new StreamWriter(requestStream);
                writer.AutoFlush = true;
                writer.Write(s);
                writer.Flush();
                writer.Close();
                requestStream.Flush();
                requestStream.Close();


                resp = null;
                try
                {
                    resp = (HttpWebResponse)request.GetResponse();
                    resp.Close();
                    Console.Write(".");
                }
                catch (WebException exception)
                {
                    StreamReader streamReader = new StreamReader(exception.Response.GetResponseStream(), true);
                    string message = streamReader.ReadToEnd();

                    Console.WriteLine(((HttpWebResponse)exception.Response).StatusDescription + "\n\n" + message);
                    return; // quit the uploads, something went wrong so there is no reason to try the rest.
                }

            } //end of forech over DEs
            Console.WriteLine();
            Console.WriteLine("done");
        }






    }
}
